<template>
  <div class="user-add-main">
    <el-form ref="addForm" :model="common" clearable filterable label-width="130px">
      <el-form-item label="题目内容:" prop="questionContent" :rules="addRules.questionContent">
        <el-input style="width: 200px" type="textarea" v-model="common.questionContent" />
      </el-form-item>
      <el-form-item label="考察点:" prop="inspectionName" :rules="addRules.inspectionName">
        <el-input style="width: 200px" v-model="common.inspectionName"  />
      </el-form-item>
      <el-form-item label="是否需要媒体文件:" prop="questionMediaStatus">
          <el-radio v-model="common.questionMediaStatus" label="1">需要</el-radio>
          <el-radio v-model="common.questionMediaStatus" label="0">不需要</el-radio>
      </el-form-item>
      <el-form-item v-if="common.questionMediaStatus == 1" label="上传媒体文件:" prop="questionMediaName" :rules="addRules.questionMediaName">
        <el-upload
          class="upload-demo"
          drag
          :action="uploadUrl"
          :headers="header"
          :on-success="handleAvatarSuccess"
          multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">上传文件,即可覆盖原有媒体文件</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="题目选项:" prop="questionOptions" :rules="addRules.questionOptions">
        <el-button type="primary" size="mini" round @click="addOptions()"><svg-icon icon-class="add" /> 添加选项</el-button>
        <el-button type="danger"  size="mini" icon="el-icon-delete" circle @click="deleteOptions()"></el-button>
      </el-form-item>
      <el-form-item v-for="(item,index) in common.questionOptions" :key="index" :label="String.fromCharCode(index+65)+':'">
        <el-input style="width: 200px" v-model="common.questionOptions[index]"  type="textarea" />
      </el-form-item>
      <el-form-item style="width: 250px" label="题目选项分值:" prop="questionOptionScore">
        <el-input type="number" min="0" max="5" v-for="(item,index) in common.questionOptionScore" v-model="common.questionOptionScore[index]" :key="index" style="margin-top: 5px;" >
          <template slot="prepend">{{String.fromCharCode(index+65)}} :</template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import commonApi from '@/api/common'
import { getToken } from '@/utils/auth'

export default {
  props: ['question'],
  data() {
    return {
      common:{
        id:"",
        questionContent: "",
        questionMediaStatus: "0",
        inspectionName: "",
        questionMediaName: [],
        questionMediaUrl:[],
        questionOptions:[],
        questionOptionScore:[],
      },
      addRules: {
        questionContent: [{ type: 'String', required: true, trigger: 'blur', validator: (rule, value, callback) => {
                if (value=="") {
                  callback(new Error('*题目不能为空!'))
                } else {
                  this.$refs['addForm'].clearValidate(['questionContent']);
                  callback()
                }
              }
        }],
        inspectionName: [{ type: 'String', required: true, trigger: 'blur', validator: (rule, value, callback) => {
                if (value=="") {
                  callback(new Error('*考察点不能为空!'))
                } else {
                  this.$refs['addForm'].clearValidate(['inspectionName']);
                  callback()
                }
              }
        }],
        questionMediaName: [{ type: 'String', required: true, trigger: 'blur', validator: (rule, value, callback) => {
                if(value.length==0){
                  callback(new Error('*请上传媒体文件!'))
                } else {
                  this.$refs['addForm'].clearValidate(['questionMediaName']);
                  callback()
                }
              }
        }],
        questionMediaUrl: [{ type: 'String', required: true, trigger: 'blur', validator: (rule, value, callback) => {
                if(value.length==0){
                  callback(new Error('*请上传媒体文件!'))
                } else {
                  this.$refs['addForm'].clearValidate(['questionMediaUrl']);
                  callback()
                }
              }
        }],
        questionOptions: [{ type: 'String', required: true, trigger: 'blur', validator: (rule, value, callback) => {
                if(value.length==0){
                  callback(new Error('*请填写选项!'))
                } else {
                  this.$refs['addForm'].clearValidate(['questionOptions']);
                  callback()
                }
              }
        }],
        questionOptionScore: [{ type: 'String', required: true, trigger: 'blur', validator: (rule, value, callback) => {
              if(value.length==0){
                callback(new Error('*请填写选项分值!'))
              } else {
                this.$refs['addForm'].clearValidate(['questionOptionScore']);
                callback()
              }
            }
        }],
      },
      header: {
        Authorization: getToken()
      },
      uploadUrl: process.env.VUE_APP_MEDIA_URL //  图片上传路径
    }
  },
 async created() {
    await commonApi.pageList({currentPage:1,pageSize:1,params:{id:this.question.id}}).then(res => {
      this.common = res.data.list[0]
    })
    if(this.common.questionMediaStatus == 0){
      this.common.questionMediaStatus = "0"
    }else{
      this.common.questionMediaStatus = "1"
    }
    for (let index = 0; index < this.common.questionOptions.length; index++) {
      this.common.questionOptions[index] = this.common.questionOptions[index].split(".")[1];
    }
    for (let index = 0; index < this.common.questionOptionScore.length; index++) {
      this.common.questionOptionScore[index] = this.common.questionOptionScore[index].split("-")[1];
    }
  },
  methods: {
    deleteOptions(){
      this.common.questionOptions.pop()
      this.common.questionOptionScore.pop()
    },
    addOptions(){
      this.common.questionOptions.push("")
      this.common.questionOptionScore.push(0)
    },
    handleAvatarSuccess(res, file) {
      this.$message.success(res.msg)
      this.common.questionMediaName = this.common.questionMediaName.concat(JSON.parse(res.data.name))
      this.common.questionMediaUrl = this.common.questionMediaUrl.concat(JSON.parse(res.data.url))
    },
    onSubmit() {
        this.$refs.addForm.validate(valid => {
        if (valid) {
          for (let index = 0; index < this.common.questionOptions.length; index++) {
            this.common.questionOptions[index] = String.fromCharCode(index+65)+"."+this.common.questionOptions[index];
          }
          for (let index = 0; index < this.common.questionOptionScore.length; index++) {
            this.common.questionOptionScore[index] = String.fromCharCode(index+65)+"-"+this.common.questionOptionScore[index];
          }
          this.common.questionMediaName = JSON.stringify(this.common.questionMediaName)
          this.common.questionMediaUrl = JSON.stringify(this.common.questionMediaUrl)
          this.common.questionOptions = JSON.stringify(this.common.questionOptions)
          this.common.questionOptionScore = JSON.stringify(this.common.questionOptionScore)
          commonApi.updateInfo(this.common).then(res => {
            this.$message.success(res.data)
            this.$emit('closeDisplay')
            this.$emit('getPageList')
            this.$refs.addForm.resetFields()
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .user-add-main{
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
